// Mock数据服务，用于开发测试
import type { RuleBasicInfo, RuleConfig, RuleListResponse, RulePreview } from '../types/rule';

// 模拟延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

// 模拟数据表
const mockTables = [
  {
    tableName: 'orders',
    tableComment: '订单表',
    fieldCount: 15,
  },
  {
    tableName: 'users',
    tableComment: '用户表',
    fieldCount: 12,
  },
  {
    tableName: 'products',
    tableComment: '产品表',
    fieldCount: 20,
  },
];

// 模拟规则列表
const mockRules: RuleBasicInfo[] = [
  {
    id: '1',
    name: '每日订单统计',
    description: '统计每日订单数量和金额',
    status: 'active',
    creator: 'admin',
    createTime: '2024-01-15 10:30:00',
    updateTime: '2024-01-15 10:30:00',
  },
  {
    id: '2',
    name: '用户活跃度分析',
    description: '分析用户活跃度和留存率',
    status: 'active',
    creator: 'admin',
    createTime: '2024-01-14 15:20:00',
    updateTime: '2024-01-14 15:20:00',
  },
  {
    id: '3',
    name: '产品销售统计',
    description: '统计产品销售情况',
    status: 'disabled',
    creator: 'user1',
    createTime: '2024-01-13 09:15:00',
    updateTime: '2024-01-13 09:15:00',
  },
];

// 模拟规则详情
const mockRuleDetail: RuleConfig = {
  basicInfo: {
    id: '1',
    name: '每日订单统计',
    description: '统计每日订单数量和金额',
    status: 'active',
    creator: 'admin',
    createTime: '2024-01-15 10:30:00',
    updateTime: '2024-01-15 10:30:00',
  },
  tables: ['orders', 'users'],
  joins: [
    {
      leftTable: 'orders',
      leftField: 'user_id',
      rightTable: 'users',
      rightField: 'id',
      joinType: 'INNER',
    },
  ],
  conditions: [
    {
      id: '1',
      tableName: 'orders',
      fieldName: 'status',
      operator: '=',
      value: 'completed',
      logic: 'AND',
    },
    {
      id: '2',
      tableName: 'orders',
      fieldName: 'created_at',
      operator: '>',
      value: '2024-01-01',
      logic: 'AND',
    },
  ],
  groupBy: [
    {
      tableName: 'orders',
      fieldName: 'created_date',
      alias: 'order_date',
    },
  ],
  aggregates: [
    {
      function: 'COUNT',
      tableName: 'orders',
      fieldName: 'id',
      alias: 'order_count',
    },
    {
      function: 'SUM',
      tableName: 'orders',
      fieldName: 'amount',
      alias: 'total_amount',
    },
  ],
};

// 模拟预览结果
const mockPreview: RulePreview = {
  estimatedRows: 365,
  estimatedTime: 150,
  sampleData: [
    {
      order_date: '2024-01-01',
      order_count: 45,
      total_amount: 12500.50,
    },
    {
      order_date: '2024-01-02',
      order_count: 52,
      total_amount: 14800.75,
    },
    {
      order_date: '2024-01-03',
      order_count: 38,
      total_amount: 10200.25,
    },
  ],
  sqlPreview: `SELECT 
  DATE(orders.created_at) AS order_date,
  COUNT(orders.id) AS order_count,
  SUM(orders.amount) AS total_amount
FROM orders
INNER JOIN users ON orders.user_id = users.id
WHERE orders.status = 'completed'
  AND orders.created_at > '2024-01-01'
GROUP BY DATE(orders.created_at)
ORDER BY order_date;`,
};

export const mockApi = {
  // 获取规则列表
  getRuleList: async (params: any): Promise<RuleListResponse> => {
    await delay(500);
    const { page = 1, size = 10, name, status, creator } = params;
    
    let filteredRules = [...mockRules];
    
    if (name) {
      filteredRules = filteredRules.filter(rule => 
        rule.name.toLowerCase().includes(name.toLowerCase())
      );
    }
    
    if (status) {
      filteredRules = filteredRules.filter(rule => rule.status === status);
    }
    
    if (creator) {
      filteredRules = filteredRules.filter(rule => 
        rule.creator && rule.creator.toLowerCase().includes(creator.toLowerCase())
      );
    }
    
    const start = (page - 1) * size;
    const end = start + size;
    const list = filteredRules.slice(start, end);
    
    return {
      list,
      total: filteredRules.length,
      page,
      size,
    };
  },

  // 获取规则详情
  getRuleDetail: async (_id: string): Promise<RuleConfig> => {
    await delay(300);
    return mockRuleDetail;
  },

  // 创建规则
  createRule: async (rule: RuleConfig): Promise<RuleBasicInfo> => {
    await delay(500);
    const newRule: RuleBasicInfo = {
      ...rule.basicInfo,
      id: Date.now().toString(),
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
    };
    mockRules.unshift(newRule);
    return newRule;
  },

  // 更新规则
  updateRule: async (id: string, rule: RuleConfig): Promise<RuleBasicInfo> => {
    await delay(500);
    const updatedRule: RuleBasicInfo = {
      ...rule.basicInfo,
      id,
      updateTime: new Date().toISOString(),
    };
    return updatedRule;
  },

  // 删除规则
  deleteRule: async (id: string): Promise<void> => {
    await delay(300);
    const index = mockRules.findIndex(rule => rule.id === id);
    if (index !== -1) {
      mockRules.splice(index, 1);
    }
  },

  // 更新规则状态
  updateRuleStatus: async (id: string, status: 'active' | 'disabled'): Promise<RuleBasicInfo> => {
    await delay(300);
    const rule = mockRules.find(rule => rule.id === id);
    if (rule) {
      rule.status = status;
      rule.updateTime = new Date().toISOString();
    }
    return rule!;
  },

  // 预览规则
  previewRule: async (_rule: RuleConfig): Promise<RulePreview> => {
    await delay(800);
    return mockPreview;
  },

  // 获取数据表列表
  getTableList: async (): Promise<any[]> => {
    await delay(300);
    return mockTables;
  },

  // 获取表字段信息
  getTableFields: async (_tableName: string): Promise<any[]> => {
    await delay(300);
    return [
      { fieldName: 'id', fieldType: 'INT', fieldComment: '主键' },
      { fieldName: 'name', fieldType: 'VARCHAR', fieldComment: '名称' },
      { fieldName: 'created_at', fieldType: 'DATETIME', fieldComment: '创建时间' },
      { fieldName: 'updated_at', fieldType: 'DATETIME', fieldComment: '更新时间' },
    ];
  },
};